<script setup>
import { ElMessage } from "element-plus";
import Layer from "@/components/layer/index.vue";
import { defineProps, ref, defineEmits, onMounted } from "vue";
import { addAPI, updateAPI } from "@/api/wedding/serviceInfo";
import { QuillEditor } from "@vueup/vue-quill";
import "@vueup/vue-quill/dist/vue-quill.snow.css";
import { dicVals } from "@/api/common";
import { upload, uploadAttach, delAPI } from "@/api/wedding/attachInfo";
import { MessagePlugin, DialogPlugin } from "tdesign-vue-next";
import { getListByPageAPI } from "@/api/wedding/serviceTypeInfo";
import { find } from "lodash";

import { getUserStore } from '@/store';

// 使用defineEmits来接收来自父组件的方法
const emit = defineEmits(["getTableData"]);
// 声明props
const props = defineProps({
  layer: {
    type: Object,
    default: () => {
      return {
        show: false,
        title: "",
        showButton: true,
      };
    },
  },
});

/************************************定义变量************************************************/
const loading = ref(false);
const ruleForm = ref(null);
const layerDom = ref(null);

//当前用户信息
const currentUser = ref(null);

const userStore1 = getUserStore();

const merchantType = ref('');
const rules = {
  type: [{ required: true, message: "请选择服务类型", trigger: "change" }],
  isDeposit: [{ required: true, message: "请选择付款方式", trigger: "change" }],
  name: [{ required: true, message: "请输入服务名称", trigger: "blur" }],
  amount: [{ required: true, message: "请输入价格", trigger: "blur" }],
  // overview: [{ required: true, message: '请输入服务概述', trigger: 'blur' }],
  details: [{ required: true, message: "请输入服务详情", trigger: "blur" }],
  address: [{ required: true, message: "请输入地址", trigger: "blur" }],
  format: [{ required: true, message: "请输入服务款式/风格/规格", trigger: "blur" }],
  // leadCar: [{ required: true, message: '请输入婚车头车', trigger: 'blur' }],
  // followCar: [{ required: true, message: '请输入婚车跟车', trigger: 'blur' }],
  createTime: [{ required: true, message: "请输入创建时间", trigger: "blur" }],
  updateTime: [{ required: true, message: "请输入修改时间", trigger: "blur" }],
};
let form = ref({
  id: null,
  userId: null,
  type: null,
  amount: null,
  name: null,
  overview: null,
  details: null,
  address: null,
  format: null,
  leadCar: null,
  followCar: null,
  createTime: null,
  updateTime: null,
  delFlag: null,
  imgUrl: null,
  file: null, // 用于存储上传的文件
  attachIds: [], // 用于存储上传的附件id
});

/************************************上传图片************************************************/
const files1 = ref([]);
const beforeUpload1 = (file) => {
  if (file.size > 5 * 1024 * 1024) {
    MessagePlugin.warning("上传的图片不能大于5M");
    return false;
  }
  return true;
};
const requestMethod1 = async (file) => {
  loading.value = true;
  console.log("[ file ] >", file);
  form.file = file.raw;
  try {
    const res = await upload(form);
    if (res.code === 0) {
      form.value.imgUrl = res.data;
      console.log("[ formqqqqqqqqqqqqqqq ] >", form);
      MessagePlugin.success("上传成功");
      loading.value = false;
      return new Promise((resolve) => {
        resolve({ status: "success", response: { url: form.imgUrl } });
      });
    }
    MessagePlugin.success(`上传失败:${res.msg}`);
    return new Promise((resolve) => {
      resolve({ status: "fail", error: "上传失败" });
    });
  } catch (er) {
    MessagePlugin.success(`上传失败:${er}`);
    return new Promise((resolve) => {
      // resolve 参数为关键代码
      resolve({ status: "fail", error: "上传失败" });
    });
  }
};

/************************************上传轮播图************************************************/
const autoUpload = ref(false);
const showImageFileName = ref(true);
const showUploadButton = ref(true);
const files = ref([]);



const beforeUpload = (file) => {
  if (file.size > 5 * 1024 * 1024) {
    MessagePlugin.warning("上传的图片不能大于5M");
    return false;
  }
  return true;
};
const requestMethod = (res) =>
  new Promise((resolve) => {
    loading.value = true;
    console.log("[ res.raw ] >", res[0].raw);
    let file = res[0];
    try {
      upload({ file: file.raw })
        .then((res) => {
          if (res.code === 0) {
            const formFile = {
              file: {},
              attachName: null,
              fileType: null,
              fileSize: null,
              sort: null,
              imgUrl: null,
            };
            formFile.attachName = file.raw.name;
            formFile.fileType = file.raw.type;
            formFile.fileSize = file.raw.size;
            formFile.filePath = res.data;
            formFile.sort = "1";
            uploadAttach(formFile)
              .then((res1) => {
                if (res1.code == 0) {
                  MessagePlugin.success("上传成功");
                  if (!Array.isArray(form.value.attachIds)) {
                    form.value.attachIds = [];
                  }
                  form.value.attachIds.push(res1.data.id);
                  loading.value = false;
                }
              })
              .catch((er) => {
                MessagePlugin.error(`上传失败:${er}`);
                return new Promise((resolve) => {
                  resolve({ status: "fail", error: "上传失败" });
                });
              });
          }
        })
        .catch((res) => {
          MessagePlugin.success(`上传失败:${res.msg}`);
          return new Promise((resolve) => {
            resolve({ status: "fail", error: "上传失败" });
          });
        });
    } catch (er) {
      MessagePlugin.success(`上传失败:${er}`);
      return new Promise((resolve) => {
        // resolve 参数为关键代码
        resolve({ status: "fail", error: "上传失败" });
      });
    }
    resolve({ status: "success" });
  });
const onRemove = (res) => {
  if (!res.file || !res.file.id) {
    return;
  }
  delAPI([res.file.id])
    .then((res) => {
      if (res.code === 0) {
        MessagePlugin.success("删除成功");
        // 从form中移除对应的attachId
        if (Array.isArray(form.value.attachIds) && form.value.attachIds.length > 0) {
          const index = form.value.attachIds.indexOf(res.file.id);
          if (index > -1) {
            form.value.attachIds.splice(index, 1);
          }
        }
      } else {
        MessagePlugin.error("删除失败");
      }
    })
    .catch((err) => {
      MessagePlugin.error(`删除失败:${err}`);
    });
};
/************************************数据回显************************************************/
if (props.layer.row) {
  if (props.layer.row) {
    let source = props.layer.row;
    Object.keys(form.value).forEach((k) => k in source && (form.value[k] = source[k]));
    files.value = source.attachInfos || ref([]);
    console.log("[ source.attachInfos ] >", source.attachInfos);
    console.log("[ attachInfos ] >", files);
  }
}

/************************************定义事件************************************************/
//提交按钮事件
let submit = () => {
  if (ruleForm) {
    ruleForm.value.validate((valid) => {
      if (valid) {
        let params = form.value;
        if (props.layer.row) {
          updateForm(params);
        } else {
          addForm(params);
        }
      } else {
        return false;
      }
    });
  }
};

let updateForm = (params) => {
  updateAPI(params).then((res) => {
    ElMessage({
      type: "success",
      message: "编辑成功",
    });
    emit("getTableData", false);
    layerDom && layerDom.value.close();
  });
};

let addForm = (params) => {
  addAPI(params).then((res) => {
    ElMessage({
      type: "success",
      message: "新增成功",
    });
    emit("getTableData", true);
    layerDom && layerDom.value.close();
  });
};
/************************************文章富文本处理************************************************/
// 编辑器配置
const editorOptions = {
  debug: "info",
  modules: {
    toolbar: [
      [{ size: [false, "small", "large", "huge"] }], // 字号
      [{ header: [false, 1, 2, 3, 4, 5, 6] }], // 标题
      [{ color: [] }, { background: [] }], // 字体颜色、文本突出显示颜色
      ["bold", "italic", "underline", "strike"], // 加粗、倾斜、下划线、删除线
      ["blockquote"], // 块引用
      [{ script: "sub" }, { script: "super" }], // 下标、上标
      [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
      [{ indent: "-1" }, { indent: "+1" }], // 减少缩进量、增加缩进量
      [{ align: [] }], // 对齐、左对齐、居中、右对齐、两端对齐
      ["link", "image", "video"], // 链接、图片、视频
      ["clean"], // 清除样式
    ],
  },
  placeholder: "请输入内容~",
};
/************************************字典初始化************************************************/
const busTypeList = ref([]);
const initDicts = async () => {
  const res = await dicVals("bus_type");
  if(merchantType.value){
  res.data.forEach((row) => {
      if(row.value === merchantType.value){
        console.log("ceshi================", merchantType.value );
        busTypeList.value.push({
          value: row.value,
          label: row.label,
        });
      }else{
        console.log("===不想等他=======")
      }

  });
  }else{
    busTypeList.value = res.data;
  }
  //

  // console.log("[ busTypeList ] >", busTypeList);
};
const paramsType = {
  current: 1,
  pageSize: 999999,
  condition: "0",
  searchValue: null,
  type: null,
};
const serviceTypes = ref([]);
const findTypeList = (searchValue) => {
  paramsType.searchValue = searchValue;
  getListByPageAPI(paramsType)
    .then((res) => {
      serviceTypes.value = res.data.list;
      // console.log("[ serviceTypes ] >", serviceTypes);
    })
    .catch((error) => {
      serviceTypes.value = [];
    });
};
const findTypeList1 = (type) => {
  paramsType.type = type;
  findTypeList();
};
/************************************下拉选择器************************************************/
const filterMethod = (search, option) => {
  return option.label.indexOf(search) !== -1;
};

// 计算属性，根据type值返回对应的标签
const getLabel = (field) => {
  console.log("[ getLabel ] >", field);
  console.log("[form.value.type >", form.value.type);
  // 默认标签
;
  if (form.value.type === "3") {
    console.log("[ getLabel ] >", field);
    if (field === 'leadCar') return '房间名称：';
    if (field === 'followCar') return '房间描述：';
  }else if (form.value.type === "1") {
    if (field === 'leadCar') return '套餐名称：';
    if (field === 'followCar') return '套餐描述：';
  } else if (form.value.type === "2") {
    if (field === 'leadCar') return '套餐名称：';
    if (field === 'followCar') return '套餐描述：';
  }
  if (field === 'leadCar') return '婚车头车：';
  if (field === 'followCar') return '婚车跟车：'
  return '';
};

// 获取对应的placeholder
const getPlaceholder = (field) => {
  if (form.value.type === 4) {
    if (field === 'leadCar') return '请输入房间名称';
    if (field === 'followCar') return '请输入房间描述';
  } else if (form.value.type === 2) {
    if (field === 'leadCar') return '请输入套餐名称';
    if (field === 'followCar') return '请输入套餐描述';
  }
  // 默认placeholder
  if (field === 'leadCar') return '请输入婚车头车';
  if (field === 'followCar') return '请输入婚车跟车';
  return '';
};

/************************************生命周期************************************************/
//获取表格数据
onMounted(async () => {
  // vue的api
  currentUser.value = userStore1.curUser;
  merchantType.value  = userStore1.curUser.merchantType;
  console.log('merchantType', merchantType.value);
  await initDicts();
  findTypeList();

});
</script>

<template>
  <Layer :layer="layer" @confirm="submit" ref="layerDom">
    <t-loading size="small" :loading="loading" showOverlay>
      <el-form
        :model="form"
        :rules="rules"
        ref="ruleForm"
        label-width="130px"
        style="margin-right: 30px"
      >
        <el-form-item label="服务类型：" prop="type">
          <el-select v-model="form.type" placeholder="请选择服务类型" @change="findTypeList1(form.type)">
            <el-option
              v-for="item in busTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="付款方式：" prop="isDeposit">
          <el-select v-model="form.isDeposit" placeholder="请选择付款方式">
            <el-option label="定金" value="0"></el-option>
            <el-option label="全款" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务名称：" prop="name">
          <el-input v-model="form.name" placeholder="请输入服务名称"></el-input>
        </el-form-item>
        <el-form-item label="服务概述：" prop="overview">
          <el-input
            type="textarea"
            v-model="form.overview"
            placeholder="请输入服务概述"
          ></el-input>
        </el-form-item>
        <el-form-item label="价格：" prop="amount">
          <el-input-number size="large" v-model="form.amount" :precision="2" :step="0.1">
            <template #suffix><span>元</span></template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="地址：" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址"></el-input>
        </el-form-item>
        <el-form-item label="服务款式/风格/规格：" prop="format">
          <t-select
            v-model="form.format"
            placeholder="请选择"
            :filter="filterMethod"
            :popupProps="{ overlayClassName: 'tdesign-demo-select__overlay-option' }"
            style="width: 300px"
          >
            <t-option
              v-for="item in serviceTypes"
              :value="item.id"
              :label="item.format"
              :key="item.id"
            >
              {{ item.format }}
            </t-option>
          </t-select>
          <!-- <el-input v-model="form.format" placeholder="请输入服务款式/风格/规格"></el-input> -->
        </el-form-item>
<!--        <el-form-item label="婚车头车：" prop="leadCar">-->
<!--          <el-input v-model="form.leadCar" placeholder="请输入婚车头车"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="婚车跟车：" prop="followCar">-->
<!--          <el-input v-model="form.followCar" placeholder="请输入婚车跟车"></el-input>-->
        <el-form-item :label="getLabel('leadCar')" prop="leadCar">
          <el-input v-model="form.leadCar" :placeholder="getPlaceholder('leadCar')"></el-input>
        </el-form-item>
        <el-form-item :label="getLabel('followCar')" prop="followCar">
          <el-input v-model="form.followCar" :placeholder="getPlaceholder('followCar')"></el-input>
        </el-form-item>

        <el-form-item label="上传商品主图：" prop="fileName">
          <t-image
            v-if="form.imgUrl"
            :src="form.imgUrl"
            mode="aspectFill"
            width="72"
            height="72"
            aria-label="图片"
          />
          <t-upload
            v-model="files1"
            :tips="'上传文件大小在 5M 以内'"
            theme="custom"
            :before-upload="beforeUpload1"
            :request-method="requestMethod1"
          >
            <t-button theme="default" variant="outline" :style="{ marginTop: '10px' }">
              <template #icon> <t-icon name="photo"></t-icon> </template
              >上传图片</t-button
            >
          </t-upload>
        </el-form-item>
        <el-form-item label="上传商品轮播图：" prop="fileName">
          <t-upload
            v-model="files"
            placeholder="支持批量上传图片文件"
            theme="image-flow"
            accept="image/*"
            multiple
            :request-method="requestMethod"
            :before-upload="beforeUpload"
            :auto-upload="autoUpload"
            :max="8"
            :abridge-name="[6, 6]"
            :show-image-file-name="showImageFileName"
            :upload-button="showUploadButton ? {} : null"
            :cancel-upload-button="showUploadButton ? { content: '取消上传' } : null"
            @remove="onRemove"
          ></t-upload>
        </el-form-item>
        <el-form-item label="服务详情：" prop="details">
          <div class="editor-container">
            <QuillEditor
              v-model:content="form.details"
              contentType="html"
              theme="snow"
              :options="editorOptions"
            />
          </div>
          <!-- <el-input v-model="form.details" placeholder="请输入服务详情"></el-input> -->
        </el-form-item>
      </el-form>
    </t-loading>
  </Layer>
</template>

<style scoped lang="scss">
.el-input-number--large {
  line-height: 38px;
  width: 230px;
}
</style>
<style lang="scss" scoped>
.editor-container {
  height: 600px;
  width: 120%;
  margin-bottom: 60px;
}

.editor-container {
  ::v-deep {
    .ql-editor {
      min-height: 600px;
      max-height: 1000px;
    }

    .ql-snow.ql-toolbar {
      .ql-picker.ql-header {
        width: 70px;

        .ql-picker-label::before,
        .ql-picker-item::before {
          content: "普通";
        }

        .ql-picker-label[data-value="1"]::before,
        .ql-picker-item[data-value="1"]::before {
          content: "标题一";
        }

        .ql-picker-label[data-value="2"]::before,
        .ql-picker-item[data-value="2"]::before {
          content: "标题二";
        }

        .ql-picker-label[data-value="3"]::before,
        .ql-picker-item[data-value="3"]::before {
          content: "标题三";
        }

        .ql-picker-label[data-value="4"]::before,
        .ql-picker-item[data-value="4"]::before {
          content: "标题四";
        }

        .ql-picker-label[data-value="5"]::before,
        .ql-picker-item[data-value="5"]::before {
          content: "标题五";
        }

        .ql-picker-label[data-value="6"]::before,
        .ql-picker-item[data-value="6"]::before {
          content: "标题六";
        }
      }

      .ql-picker.ql-size {
        width: 70px;

        .ql-picker-label::before,
        .ql-picker-item::before {
          content: "普通";
        }

        .ql-picker-label[data-value="small"]::before,
        .ql-picker-item[data-value="small"]::before {
          content: "小";
        }

        .ql-picker-label[data-value="large"]::before,
        .ql-picker-item[data-value="large"]::before {
          content: "中";
        }

        .ql-picker-label[data-value="huge"]::before,
        .ql-picker-item[data-value="huge"]::before {
          content: "大";
        }
      }
    }

    .ql-snow .ql-tooltip::before {
      content: "链接";
    }

    .ql-snow .ql-tooltip a.ql-action::after {
      content: "编辑";
    }

    .ql-snow .ql-tooltip.ql-editing a.ql-action::after {
      content: "保存";
    }

    .ql-snow .ql-tooltip a.ql-remove::before {
      content: "移除";
    }
  }
}
</style>
